package com.piece.admin.controller.front;

import com.piece.core.framework.constant.ApplicationConstants;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.constant.ParamConstants;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.framework.properties.ApplicationProperties;
import com.piece.core.verifycode.processor.ValidateCodeProcessorHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Api(tags = {"验证码管理"})
@RestController
public class ValidateCodeController {

    @Autowired
    private ApplicationProperties applicationProperties;

    @Autowired
    private ValidateCodeProcessorHolder validateCodeProcessorHolder;

    @GetMapping("/public/client_code/check")
    @ApiOperation(value = "检查是否需要验证码")
    @ApiImplicitParam(name = "client_id", value = "客户端ID")
    public AjaxResponse checkClientValidateCode(HttpServletRequest request) {
        boolean needValidate = true;
        String clientId = request.getParameter(ParamConstants.CLIENT_ID);
        String ignore = applicationProperties.getValue(ApplicationConstants.CLIENT_IGNORE_VALIDATE);

        if (null != clientId && null != ignore) {
            if (StringUtil.getIndexOfString(clientId, Convert.toStrArray(ignore)) != -1) {
                needValidate = false;
            }
        }

        return AjaxResponse.success(I18nUtil.message(ExceptionConstants.MESSAGE_SUCCESS), needValidate);
    }

    @GetMapping("/authentication/code/{type}")
    @ApiOperation(value = "创建验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "验证码类别", allowableValues = "captcha,sms", paramType = "path"),
            @ApiImplicitParam(name = "captcha_type", value = "验证码生成规则", allowableValues = "char,math"),
            @ApiImplicitParam(name = "validate_code_session", value = "唯一识别码"),
            @ApiImplicitParam(name = "mobile", value = "手机号")
    })
    public void createCode(HttpServletRequest request, HttpServletResponse response, @PathVariable String type) throws Exception {
        this.validateCodeProcessorHolder.findValidateCodeProcessor(type).create(request, response);
    }
}
